﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Localization;
using Sunlit.Business.Authorization.Permissions.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sunlit.Business.Authorization.Permissions
{
    public class PermissionAppService : BusinessAppServiceBase, IPermissionAppService
    {
        private readonly ILocalizationContext _localizationContext;
        public PermissionAppService(ILocalizationContext localizationContext)
        {
            _localizationContext = localizationContext;
        }
        public ListResultDto<TreePermissionDto> GetAllPermissinsForTree()
        {
            var permissions = PermissionManager.GetAllPermissions();
            var rootPermissions = permissions.Where(p => p.Parent == null);

            var result = new List<TreePermissionDto>();

            foreach (var rootPermission in rootPermissions)
            {
                var treePermission = new TreePermissionDto
                {
                    Title = rootPermission.DisplayName.Localize(_localizationContext),
                    Name = rootPermission.Name,
                    Expand = true
                };
                result.Add(treePermission);
                AddTreePermission(treePermission, rootPermission, permissions);
            }
            return new ListResultDto<TreePermissionDto>
            {
                Items = result
            };
        }
        private void AddTreePermission(
            TreePermissionDto treePermission,
            Permission permission,
            IReadOnlyList<Permission> allPermissions)
        {
            if (permission.Children == null)
            {
                return;
            }
            var children = allPermissions.Where(p => p.Parent != null && p.Parent.Name == permission.Name).ToList();

            treePermission.Children = new List<TreePermissionDto>();
            foreach (var childPermission in children)
            {
                var childTreePermission = new TreePermissionDto
                {
                    Title = childPermission.DisplayName.Localize(_localizationContext),
                    Name = childPermission.Name,
                    Expand = true
                };
                treePermission.Children.Add(childTreePermission);
                AddTreePermission(childTreePermission, childPermission, allPermissions);
            }
        }
    }
}
